<?php
/**
 * sample data object:
 * {
 * 	user_id: ...,
 * 	loan: ...,
 * 	contract: ...,
 * 	push: [0|1],
 * 	shifts: [
 * 		{
 * 			year: ...,
 * 			week: ...,
 * 			day: ...,
 * 			start: ...,
 * 			end: ...,
 * 			type: [0|1|2]
 * 		}
 *  ]	
 * }
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST'
		|| !(isset($_POST['user_id']) || isset($_POST['data']))) {
	header("HTTP/1.1 400 Bad Request");
	exit;
}
require_once 'db.inc.php';

if (isset($_POST['data'])) {
	$data = json_decode($_POST['data']);
	
	$sql = "UPDATE ".TABLE_PREFIX."users SET contract = ".$data->{"contract"}.", 
			loan = ".$data->{'loan'}.", push = ".$data->{'push'}."
			WHERE id = ".$data->{'user_id'};
	mysql_query($sql) or die(mysql_error());
	foreach ($data->{'shifts'} as $shift) {
		mysql_query(sprintf("INSERT INTO ".TABLE_PREFIX."shifts (user, year, week, day, start, end)
				VALUES(%d, %d, %d, %d, %f, %f)", 
				$data->{'user_id'},
				$shift->{'year'}, $shift->{'week'}, $shift->{'day'},
				$shift->{'start'}, $shift->{'end'}));
	}
	header("HTTP/1.1 201 Created");
} else {
	$result = mysql_query("SELECT * FROM ".TABLE_PREFIX."users WHERE id = ". $_POST['user_id']);
	if (!result || mysql_num_rows($result) !== 1) {
		header("HTTP/1.1 404 Not Found");
		exit;
	}
	
	$reply = array(
			'user_id' => mysql_result($result, 0, 'id'),
			'contract' => mysql_result($result, 0, 'contract'),
			'loan' => mysql_result($result, 0, 'loan'),
			'push' => mysql_result($result, 0, 'push'),
			'shifts' => array()
	);
	
	$result = mysql_query("SELECT * FROM ".TABLE_PREFIX."shifts WHERE user = ". $reply['user_id']) or die(mysql_error());
	
	while ($row = mysql_fetch_assoc($result)) {
		$reply['shifts'][] = $row;
	}
	//header("Content-Type: application/json");
	echo json_encode($reply);
}
?>